namespace EyeOpen.SampleCms.Web.Data.Serialization
{
    using System;
    using System.IO;
    using System.Xml.Serialization;

    public class XmlSerializer<T> : Serializer<T>
    {
        private readonly string fileName;

        public XmlSerializer(string fileName)
        {
            this.fileName = fileName;

            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName", "File name cannot be null.");
            }
        }

        public string FileName
        {
            get
            {
                return fileName;
            }
        }

        public override T Deserialize()
        {
            using (var stream = File.OpenRead(fileName))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                return (T)xmlSerializer.Deserialize(stream);
            }
        }

        public override void Serialize(T value)
        {
            using (var stream = File.OpenWrite(fileName))
            {
                var xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(stream, value);
            }
        }
    }
}